﻿using System;
using Cngot.Extensions.EventBus.Kafka.Integration;

namespace Cngot.Extensions.Logger.Kafka
{
    internal class KafkaLogger : BaseLogger
    {
        private readonly KafkaLoggerOptions loggerOptions;
        private readonly KafkaProducer producer;
        public KafkaLogger(IServiceProvider serviceProvider, string category, KafkaLoggerOptions options, KafkaProducer producer) : base(serviceProvider, category)
        {
            this.loggerOptions = options;
            this.producer = producer;
        }
        /// <summary>
        /// 释放
        /// </summary>
        public override void Dispose()
        {
            base.Dispose();
        }
        public override void WriteLog<TState>(Func<TState, Exception, string> formatter, LoggerMessage formatMessage)
        {
            try
            {
                producer.Publish(new KafkaMessage()
                {
                    Key = Guid.NewGuid().ToString("N"),
                    Partition = loggerOptions.Partition,
                    Body = formatMessage
                });
            }
            catch (Exception ex)
            {
                do
                {
                    Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
                } while ((ex = ex.InnerException) != null);
            };
            base.WriteLog(formatter, formatMessage);
        }
    }
}
